<script setup>
import { getCurrentInstance, onMounted, onUnmounted, onUpdated, ref, watch } from "vue";
import eventBus from '../../event/eventBus.js';
import { addLayer, addLabelLayer, removeLayer,  addOverlay,
  removePopup, } from '@/components/map/map'

const NAME = '图层管理';
import { getAxios } from '@/api/global'
let showLayer = ref(false);
let  popLayer = []
let wrjpopLayer = []
const checkList = ref([
  {
    name: '视频监控',
    img: '视频监控',
    serverName: 'vedio',
    isCheck: false
  },
  {
    name: '无人机',
    img: '无人机',
    serverName: 'wurenji',
    isCheck: false
  },
  {
    name: '水文站',
    img: '水文站',
    serverName: 'shuiwenzhan0924',
    isCheck: false
  },
  {
    name: '水位站',
    img: '水位站',
    serverName: 'shuiweizhan0924',
    isCheck: false

  },
  {
    name: '雨量站',
    img: '雨量站',
    serverName: 'jiangyuliangzhan0924_注记',
    isCheck: false
  },
  {
    name: '水闸',
    img: '水闸',
    serverName: 'shuizha0924_注记',
    isCheck: false
  },
  {
    name: '大型水库',
    img: '大型水库',
    serverName: 'daxingshuiku0924_注记',
    isCheck: false
  },
  {
    name: '中型水库',
    img: '中型水库',
    serverName: 'zhongxingshuiku0924_注记',
    isCheck: false
  },
  {
    name: '小型水库',
    img: '小型水库',
    serverName: 'xiaoxingshuiku0924_注记',
    isCheck: false
  },
  {
    name: '危险区',
    img: '危险区',
    serverName: 'weixianqu0924',
    isCheck: false
  },
  {
    name: '泵站',
    img: '泵站',
    serverName: 'bengzhan0924_注记',
    isCheck: false
  },
  {
    name: '排渍站',
    img: '排渍站',
    serverName: 'paizizhan0924_注记',
    isCheck: false
  }
])
const checkVlaue = ref([])
let imageryProvider1 = null;
let imageryProvider2 = null;
const { appContext } = getCurrentInstance();
let global = appContext.config.globalProperties;

onMounted(() => {
  eventBus.on('mapToolBarClick', (data) => {
    if (data == NAME) {
      showLayer.value = !showLayer.value;
    } else {
      showLayer.value = false;
      destroyAll()
    }
  });
});
watch(() => checkVlaue.value, (val, old) => {
  let poinatarr = ['vedio', 'wurenji']
  if (val.includes('vedio') && popLayer.length == 0) {
    getVideoMonitorData()
  }

  if (val.includes('wurenji') && wrjpopLayer.length == 0) {
    getUavMonitorData()
  }

  if(!val.includes('vedio')){
    removePopup(popLayer)
    popLayer = []
  }
   if(!val.includes('wurenji')){
    removePopup(wrjpopLayer)
    wrjpopLayer = []
  }
  let layers = []
  let labelLAyers = []
  val.forEach(serverName => {
    if (serverName.indexOf('注记') > -1) {
      let str = serverName.slice(0, -3) || ''
      labelLAyers.push({
        display: true,
        id: str
      })
    } else if (!poinatarr.includes(serverName)) {
      layers.push({
        display: true,
        id: serverName || ''
      })
    }
  })
  destroyLayer()
  updatedLegend(layers, labelLAyers)
})
onUnmounted(() => {
  destroyLayer()
})
const destroyLayer = () => {
  removeLayer(global.$viewer, imageryProvider1)
  removeLayer(global.$viewer, imageryProvider2)
  imageryProvider1 = null;
  imageryProvider2 = null;
}

const updatedLegend = (layers, labelLAyers) => {
  if (layers.length > 0) {
    let filter = {
      layers,
      order: [],
      otherDisplay: false,
    };
    let control = encodeURIComponent(JSON.stringify(filter));
    const url = 'http://119.45.166.244:40021/mapserver/layer/定制服务0924/getMAP?x={TileCol}&y={TileRow}&l={TileMatrix}&styleId=dzfw0924&control=' + control;
    imageryProvider1 = addLayer(global.$viewer, url)
  }

  if (labelLAyers.length > 0) {
    let labelFilter = {
      layers: labelLAyers,
      order: [],
      otherDisplay: false,
    }
    const labelControl = encodeURIComponent(JSON.stringify(labelFilter));
    const labelUrl = 'http://119.45.166.244:40021/mapserver/label/定制服务0924/getDatas?&x={x}&y={y}&l={z}&tilesize=512&styleId=dzfw0924&control=' + labelControl
    imageryProvider2 = addLabelLayer(global.$viewer, labelUrl)
  }
}
const destroyAll = () => {
  // 销毁
  checkVlaue.value = []
}
const getUavMonitorData = async () => {
  const res = await getAxios('data/json/无人机飞行编制数据.json')
  let data = res.drone_flight_records

  addVideoOverlay(data, 'wrj')
}

//获取视频监控数据
const getVideoMonitorData = async () => {
  const res = await getAxios('data/json/视频监控.json')
  let data = res.monitoring_events
  addVideoOverlay(data, 'sp')
}

//加载视频监控点位
const addVideoOverlay = (data, type) => {
  let baseElement = document.getElementsByClassName('overlay-pop')[0]
  if (type == 'sp') {
    baseElement = document.getElementsByClassName('overlay-pop')[0]
  } else if (type == 'wrj') {
    baseElement = document.getElementsByClassName('wrjoverlay-pop')[0]
  }

  data.forEach((item, i) => {
    item.strType = type
    const element = baseElement.cloneNode(true) // ✅ 深度克隆
      element.addEventListener('click', function(e) {
            if(item.strType === 'sp'){
                eventBus.emit('shipinClick',item);
            }else  if(item.strType === 'wrj'){
                eventBus.emit('wurenjiClick',item);
            }
      
    });
    if (type == 'sp') {
      let position = Cesium.Cartesian3.fromDegrees(
        item.coordinates[0],
        item.coordinates[1],
        0
      )
      popLayer[i] = addOverlay(global.$viewer, element, position)
    } else if (type == 'wrj') {
      let position = Cesium.Cartesian3.fromDegrees(
        item.alert_coordinates[0],
        item.alert_coordinates[1],
        0
      )
      wrjpopLayer[i] = addOverlay(global.$viewer, element, position)
    }

  })
}

</script>

<template>
  <div v-if="showLayer" class="layer" style="box-shadow: var(--el-box-shadow-light)">
    <el-checkbox-group v-model="checkVlaue">
      <el-checkbox :label="item.name" :value="item.serverName" v-for="item in checkList" :key="item.serverName" />
    </el-checkbox-group>
  </div>

</template>
<style lang="less" scoped>
.layer {
  ::v-deep(.el-checkbox-group) {
    background: rgba(8, 22, 56, 0.9);
    border-radius: 0.2rem;
    padding: 0.6rem;

    .el-checkbox {
      display: flex;
      color: #fff;
      margin-right: 10px;
    }
  }
}
</style>